package com.dmall.graph.dfs.app;

import com.dmall.graph.Graph;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;

/**
 * @author: xiao1.wang
 * @date: 2022/6/19 14:26
 */
public class SingleSourcePath2 {

    private Graph G;
    private boolean[] visited;
    private int[] pre;
    private int s;
    private int t;

    public SingleSourcePath2(Graph G, int s, int t) {
        G.validateVertex(s);
        G.validateVertex(t);
        this.G = G;
        this.s = s;
        this.t = t;
        this.visited = new boolean[G.V()];
        this.pre = new int[G.V()];

        Arrays.fill(this.pre, -1);
        dfs(s, s);
    }

    private boolean dfs(int v, int p) {
        this.visited[v] = true;
        this.pre[v] = p;
        if (v == t) {
            return true;
        }
        for (Integer w : G.adj(v)) {
            if (!visited[w]) {
                if (dfs(w, v)) {
                    return true;
                }
            }
        }
        return false;
    }

    public boolean isConnected() {
        return visited[t];
    }

    public Iterable<Integer> path() {
        ArrayList<Integer> path = new ArrayList<>();
        if (!isConnected()) {
            return path;
        }
        int cur = t;
        while (cur != s) {
            path.add(cur);
            cur = pre[cur];
        }
        path.add(s);
        Collections.reverse(path);
        return path;
    }

    public static void main(String[] args) {
        String filePath = SingleSourcePath2.class.getClassLoader().getResource("g.txt").getPath();
        Graph graph = new Graph(filePath);
        SingleSourcePath2 singleSourcePath = new SingleSourcePath2(graph, 0, 6);
        System.out.println(singleSourcePath.isConnected());
        System.out.println(singleSourcePath.path());
        SingleSourcePath2 singleSourcePath2 = new SingleSourcePath2(graph, 0, 5);
        System.out.println(singleSourcePath2.isConnected());
        System.out.println(singleSourcePath2.path());
    }
}
